import { notification } from 'ant-design-vue';
import { ref, Ref } from 'vue';
//https://juejin.cn/post/6888925879243079687
export default function useApi(api: Function) {
  const loading = ref(false);
  const result = ref(null);
  const error = ref(null);

  const fetchResource = (params: any) => {
    loading.value = true;
    return api(params)
      .then((data: any) => {
        // 按照约定，api返回的结果直接复制给result
        result.value = data;
      })
      .catch((e: any) => {
        error.value = e;
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const doDelete = async (del: Function, id: number, dataSource: Ref, page: Ref, reload: Ref) => {
    try {
      const ids = [id];
      await del(ids);

      if (dataSource.value.length == ids.length && page.value > 0) {
        --page.value;
      } else {
        reload.value = !reload.value;
      }

      notification['success']({
        message: '删除成功!',
        duration: 3,
      });
    } catch (error) {}
  };

  return {
    loading,
    error,
    result,
    fetchResource,
    doDelete,
  };
}
